﻿defClass(happyfarm.util, "Tools", null, function(Tools, Tools_prototype){
    Tools_prototype.init = function(){
    	
    };
    
    Tools_prototype.getServerTime = function(){
        var c = new Date();
        return Math.floor((c.getTime() + difTime)/1000);
        //document.write("<br><b>还原到原始日期为</b>: "+datum.toLocaleString());
    };
	
	Tools_prototype.getLocalTime = function(){
        var c = new Date();
        return Math.floor(c.getTime()/1000);
        //document.write("<br><b>还原到原始日期为</b>: "+datum.toLocaleString());
    };
	
	Tools_prototype.setTimeDif = function(serverTime){
		if(serverTime){
			var s = new Date(serverTime);
			var c = new Date();
			difTime = s.getTime() - c.getTime();
		}
    };
    
    Tools_prototype.converTime = function(time){
        var dateTime = new Date(time);
        var dateArray = new Array();
        dateArray[0] = dateTime.getFullYear();
        dateArray[1] = parseInt(dateTime.getMonth()) + 1;
        dateArray[2] = dateTime.getDate();
        dateArray[3] = dateTime.getHours();
        dateArray[4] = dateTime.getMinutes();
        dateArray[5] = dateTime.getSeconds();
        var datum = new Date(Date.UTC(dateArray[0], dateArray[1] - 1, dateArray[2], dateArray[3] - 8, dateArray[4], dateArray[5]));
        return datum.getTime() / 1000;
    };
    
    
    Tools_prototype.toUnixTime = function(time){
        var datum = new Date(time * 1000);
        datum = new Date(datum.getTime());
        return datum.toLocaleString();
    };
    
    Tools_prototype.getTimeFormat = function(time, format){
        time = new Date(time * 1000).format(format);
        return time;
    };
    
    Tools_prototype.culTime = function(nSeconds){
        var nTotal = nSeconds - 1;
        
        var str = "";
        if (nSeconds <= 0) {
            str = "-";
        } else {
            var days = Math.floor(nSeconds / (24 * 60 * 60));
            nSeconds = nSeconds - days * 24 * 60 * 60;
            var hours = Math.floor(nSeconds / (60 * 60));
            nSeconds = nSeconds - hours * 60 * 60;
            var munites = Math.floor(nSeconds / 60);
            seconds = nSeconds - munites * 60;
            if (days > 0) 
                str = str + days + "天";
            if (hours > 0 || str != "") {
                if (hours < 10) {
                    hours = "0" + hours;
                }
                str = str + hours + ":";
            } else {
                str = str + "00:";
            }
            
            if (munites > 0 || str != "") {
                if (munites < 10) {
                    munites = "0" + munites;
                }
                str = str + munites + ":";
            } else {
                str = str + "00:";
            }
            
            if (seconds < 10) {
                seconds = "0" + seconds;
            }
            str = str + seconds;
        }
        return str;
    };
    
    //等级计算
    Tools_prototype.getLevel = function(experience){
        var levelArray = new Array(2);
        levelArray[0] = 0;
        levelArray[1] = 0;
        for (var i = 1; i < 100; i++) {
            levelArray[0] += 200 + 200 * (i - 1);
            if (levelArray[0] > experience) {
                //取得升级所需经验
                levelArray[1] = levelArray[0] - experience;
                //取得当前级别
                levelArray[0] = i - 1;
                break;
            }
        }
        return levelArray;
    };
    
    //取得XML记录
    Tools_prototype.getConfig = function(path, fct){
        var xmlDoc;
        try {
            if (navigator.userAgent.indexOf("MSIE") > 0) {
                // code for IE
                var ActiveX = new Array("MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XMLDOM", "MSXML.DOMDocument");
                for (var i = 0; i < ActiveX.length; i++) {
                    try {
                        xmlDoc = new ActiveXObject(ActiveX[i]);
                    } catch (e) {
                    }
                }
                xmlDoc.async = false;
                xmlDoc.load(path);
            } else if (document.implementation.createDocument) {
                // code for Firefox, Mozilla, Opera, etc.
                xmlDoc = document.implementation.createDocument("", "", null);
                xmlDoc.async = false;
                xmlDoc.load(path);
            }
        } catch (error) {
            //alert(error);
        } finally {
            fct(xmlDoc);
        }
    };
    
    //保存配置文件
    Tools_prototype.saveConfig = function(content, fileName, path, alt){
        //为每个用户建立一个专有文件夹
		var userPath = this.getURI();
        userPath = userPath + myId;
        //IE浏览器
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            var fso, f;
            fso = new ActiveXObject("Scripting.FileSystemObject");
            if (!fso.FolderExists(userPath)) {
                fso.CreateFolder(userPath);
            }
            //创建好友配置文件
			if(path){
				userPath = this.getURI();
			}
            var userConfig = fso.BuildPath(userPath, fileName + ".config");
            f = fso.CreateTextFile(userConfig, true);
            f.Write(content);
            f.Close();
        } else if (navigator.userAgent.indexOf("Firefox") > 0) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            
            var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            //确定文件，解决火狐路径乱码
			if(path){
				userPath = this.getURI();
			}
            file.initWithPath(userPath.replace(/\//gi, "\\") + "\\" + fileName + ".config");
            if (file.exists() == false) {
                //alert( "Creating file... " );
                file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420);
            }
            var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
            outputStream.init(file, 0x04 | 0x08 | 0x20, 420, 0);
            
            var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
            converter.charset = 'UTF-8';
            var xmlDoc = document.implementation.createDocument("", "", null);
            var convSource = converter.ConvertFromUnicode(content);
            var result = outputStream.write(convSource, convSource.length);
            outputStream.close();
        }
		if(alt){
        	alert("保存成功！");
		}
    };
    
    //取得当前路径
    Tools_prototype.getURI = function(){
        var url = window.location.toString();
        url = decodeURI(url);
        var uri = url.substring(8, url.lastIndexOf("/") + 1);
        return uri;
    };
    
    //获得验证码
    Tools_prototype.getKey = function(){
        var farmTime = this.getServerTime();
		var key = "LHGHqwdsdfgHQKtL6b6gsESuck";
		//var key = "JomMqwdQKtL6b6gsEWAO";
        //var key = "fs#$hsJ!Fa*AF!-0aPS";
		//var key = "derrywangbillyliallenfengjiajialiu";
		//var key = "allenfengjiajialiuderrywangbillyli2012";
		//var key = "billyliallenfengjiajialiuderrywang0128";
        var farmKey = hex_md5(farmTime + key.substr(parseInt(farmTime) % 10, key.length));
        key = "farmKey=" + farmKey + "&farmTime=" + farmTime;
        return key;
    };
    
    //升级检测
    Tools_prototype.checkUpgrade = function(){
        var request = new happyfarm.util.Request();
        var version = this.getVersion();
        var url = "http://www.savefarmer.cn/version/qq_happyfarm.txt?r="+Math.random();
        request.doGetCommon(url, function(result){
			result = result.responseText;				   
			if (result.indexOf("V") != 0) {
				return;
			}
            if (result != version) {
                document.getElementById("version").innerHTML = "当前版本" + version + "，升级后版本" + result;
                openDialog("upgradeDialog");
            }									   
		});
    };
    
    Tools_prototype.getVersion = function(){
        return "V1.0";
    };
});
